package com.ch.d0304;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

@WebFilter(filterName = "LoginFilter",
            value = {"/hello.html","/pub/check.html","/UploadServlet"})
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println("EncodingFilter 初始化");
    }

    public void destroy() {
        System.out.println("EncodingFilter 销毁");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        chain.doFilter(request, response);
        //判断是否登录 =》 在会会话中查找 loginedUser 属性
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpSession session = httpServletRequest.getSession();
        if(session.getAttribute("loginUser") == null){
            //说明未登录
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            // 获取应用上下文对象
            ServletContext servletContext = request.getServletContext();
            // contextPath => /123start
            String contextPath = servletContext.getContextPath();
            //使用绝对路径访问 登录页面
            //编码
            String url = URLEncoder.encode("验证码","utf-8") + ".html";
            //跳转登录页面
            httpServletResponse.sendRedirect(url);

            //保存当前访问的页面地址
            String requestURI = httpServletRequest.getRequestURI();
            System.out.println("requestURI = " + requestURI);
            // 将返回地址保存到会话
            session.setAttribute("requestURI",requestURI);
            //返回 ，不允许访问目标资源 ，不能执行 chain.doFiler...
            return;
        }
        System.out.println("LoginFilter 执行过滤(前)");
        chain.doFilter(request,response);
        System.out.println("LoginFilter 执行过滤(后)");
    }
}
